﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.IService;
using Admin.Model;
using Admin.Model.ResponseModel;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;

namespace Admin.Web.Controllers.Api
{
    public class SysMenuController : ApiController
    {
        private ISysMenuService _sysMenuService;
        private ISysRoleMenuService _sysRoleMenuService;
        private IMapper _mapper;
        public SysMenuController(ISysRoleMenuService sysRoleMenuService, ISysMenuService sysMenuService, IMapper mapper)
        {
            _mapper = mapper;
            _sysMenuService = sysMenuService;
            _sysRoleMenuService = sysRoleMenuService;
        }

        /// <summary>
        /// 菜单列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="visible"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryMenuList(string name, int? visible)
        {
            #region 查询条件
            string sqlWhere = "";
            if (name != null)
            {
                sqlWhere = $"{sqlWhere} and Name like concat('%', @name, '%')";
            }
            if (visible != null)
            {
                sqlWhere = $"{sqlWhere} and Visible = @visible";
            }
            #endregion

            var rows = await _sysMenuService.GetList(new { name, visible }, sqlWhere, "");
            return Ok(rows);
        }
        [HttpGet]
        public async Task<InfoModel> QueryMenuZtreeData(int? roleId = null)
        {
            var rows = await _sysMenuService.GetList();
            var Data = _mapper.Map<List<MenuZtree>>(rows);
            if (roleId != null)
            {
                var menu = await _sysRoleMenuService.GetList(new { RoleId = roleId }, "RoleId=@RoleId", "");
                foreach (MenuZtree tree in Data)
                {
                    int count = menu.Where(o => o.MenuId == tree.Id).Count();
                    if (count > 0)
                    {
                        tree.Checked = true;
                    }
                }
            }
            return DataReturn(Data, "树形菜单");
        }
    }
}